<script setup lang="ts">
import { defineProps, ref } from "vue"
import UniversalComment from "@/components/CommentSection/UniversalComment.vue"
import { getArticleCommentsAPI, publishCommentCompatAPI } from "@/api/web/comment"
import { ElMessage } from "element-plus"

// 接受父组件传递过来的数据
const props = defineProps<{
  id: string
}>()

// 通用评论组件引用
const universalCommentRef = ref()

// 处理评论发布
const handleSubmitComment = async (commentData: any) => {
  try {
    console.log('发布评论数据:', commentData)
    // 调用社区评论发布API（使用兼容接口）
    const res = await publishCommentCompatAPI({
      articleID: props.id,
      nickname: commentData.nickname,
      content: commentData.content,
      address: commentData.ip || '',
      time: commentData.time
    })

    if ((res as any).code === 200) {
      ElMessage.success("评论发布成功")
      // 调用通用组件的成功回调
      universalCommentRef.value?.handleCommentSubmitSuccess()
    }
  } catch (error) {
    console.error('评论发布失败:', error)
    // 调用通用组件的失败回调
    universalCommentRef.value?.handleCommentSubmitError(error)
  }
}

// 处理获取评论列表
const handleGetCommentList = async (params: any) => {
  try {
    console.log('获取评论列表参数:', params)

    // 调用社区评论列表API
    const res = await getArticleCommentsAPI(params.articleId, params.page, params.pageSize)

    if (res.data) {
      // 处理不同的响应格式
      const comments = Array.isArray(res.data) ? res.data : res.data.data || []
      const total = res.data.total || 0

      // 调用通用组件的数据处理方法
      universalCommentRef.value?.handleCommentListData({
        comments,
        total
      })
    } else {
      console.warn('获取评论列表返回空数据')
      universalCommentRef.value?.handleCommentListData({ comments: [], total: 0 })
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    universalCommentRef.value?.handleCommentListData({ comments: [], total: 0 })
  }
}

// 处理评论更新
const handleCommentUpdate = (change: number) => {
  console.log('评论数量变化:', change)
}

// 处理评论添加
const handleCommentAdded = () => {
  console.log('新评论已添加')
}
</script>
<template>
  <UniversalComment
    ref="universalCommentRef"
    :article-id="props.id"
    article-type="community"
    status="web"
    :show-emoji="true"
    :show-location="false"
    :show-collapse="true"
    @update="handleCommentUpdate"
    @comment-added="handleCommentAdded"
    @submit-comment="handleSubmitComment"
    @get-comment-list="handleGetCommentList"
  />
</template>

